
<div class="row">
    <form id="add_wrk_ord" class="form-horizontal"  method="post">
      <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Add Work Order</i></h5>
        <div class="ibox-tools">
            <button  id="sads" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <a id="cancel_add" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
            <a style="display:none;" id="complete_btn" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Complete</a>
        </div>
      </div>
        <div class="ibox-content">

            <div class="form-group">
                <label class="col-lg-3 control-label">Maintenance Type</label>
                    <div class="col-lg-4">
                        <select id="wrk_typ" class="chosen-select" name="wo_maintain_type">
                        <?php $tae = 1; foreach ($wo_type as $wo) { $igit = ''; if($tae == 1){$igit = 'selected';}?>
                            <option value="<?php echo $wo->lookup_code;?>" <?php echo $igit; ?>><?php echo $wo->meaning; ?></option>
                        <?php $tae++;}?>
                    </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Account Name</label>
                    <div class="col-lg-4">
                        <select id="acct_name" class="chosen-select" name="wo_acct_name">
                        </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Assigned to</label>
                    <div class="col-lg-4">
                        <select id="assgn_to" class="chosen-select" name="wo_assign">
                        <?php foreach ($assgn as $op) {?>
                            <option value="<?php echo $op->user_id; ?>" ><?php echo $op->user_name; ?></option>
                        <?php }
?>
                        </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Target Date</label>
                    <div class="col-lg-4">
                        <input type="search" placeholder="" name="wo_target_date" id="t_date" class="form-control">
                    </div>
            </div><br>
            <button style="display:none;" id="add_dev_btn" type="button" class="btn btn-w-m btn-info add-tab-btn">Add Device</button></h4>
        </div>
    </form>
<input type="hidden" id="acct_id">
<input type="hidden" id="maintain_id">

  <div style="display: none;" id="device_window">
    <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Add Device</i></h5>
        <div class="ibox-tools">
            <button id="save_device" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <button id="cancel_add_device" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</button>
        </div>
    </div>
    <div class="ibox-content">
       <form class="form-horizontal" id="device_form">
          <div class="form-group">
              <label class="col-lg-3 control-label">Item Number</label>
              <div class="col-lg-7">
                  <select class="form-control m-b chosen-select" name="item_num">
                      <option value="">Select Item Number</option>
                      <?php foreach ($item as $i): ?>
                      <option value="<?php echo $i->item_id; ?>"><?php echo $i->item_num; ?></option>
                      <?php endforeach;?>
                  </select>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Device Type</label>
              <div class="col-lg-7">
                  <select class="form-control m-b chosen-select" name="dev_type">
                      <option value="">Select Device Type</option>
                      <?php foreach ($devtype as $dt): ?>
                      <option value="<?php echo $dt->type; ?>"><?php echo $dt->meaning; ?></option>
                      <?php endforeach;?>
                  </select>
              </div>
          </div>
           <div class="form-group">
              <label class="col-lg-3 control-label">Model Number</label>
              <div class="col-lg-7">
                  <input type="text" name="model_number" class="form-control">
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Serial Number</label>
              <div class="col-lg-7">
                  <input type="text" name="serial_number" class="form-control">
              </div>
          </div>
           <div class="form-group">
              <label class="col-lg-3 control-label">Device ID</label>
              <div class="col-lg-7">
                  <input   type="text" name="dev_id" class="form-control">
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Location Latitude</label>
              <div class="col-lg-7">
                  <input type="text" name="devLat" placeholder="Point your location in the map below" value="0" class="form-control" id="dlat" readonly >
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Location Longitude</label>
              <div class="col-lg-7">
                  <input type="text" name="devLng" placeholder="Point your location in the map below" value="0" class="form-control" id="dlng" readonly >
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Pick Location</label>
              <div class="col-lg-6">
                  <div id="map_wrapper" style="height: 300px;">
                      <div id="map_canvas" class="mapping" style="width: 100%;height: 100%;">
                      </div>
                  </div>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Device Remarks</label>
              <div class="col-lg-7">
                  <input type="text" name="dev_remarks" class="form-control">
              </div>
          </div>
      </form>
    </div><!-- end ofibox-content -->
  </div>
  <!-- <input id="add_dev_click" type="hidden" value="1"> -->
</div>
<script>
    $(document).ready(function(){
        $(".chosen-select").chosen({width:"100%;"});
        get_acct();
        var markers =[];

        function initialize() {
           var mapProp = {
            center:new google.maps.LatLng(8.397371738287157,124.5965675264597),
            zoom:17,
            mapTypeId:google.maps.MapTypeId.SATELITE
          };
          var map=new google.maps.Map(document.getElementById("map_canvas"),mapProp);
            google.maps.event.addDomListener(window, 'load', initialize);

          map.addListener('click', function(e) {
            placeMarkerAndPanTo(e.latLng, map);
          });  
        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        }


        function placeMarkerAndPanTo(latLng, map) {
          DeleteMarkers();
          var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });
          map.panTo(latLng);

          markers.push(marker);
          $('#dlat').val(latLng.lat());
          $('#dlng').val(latLng.lng());

        }


        function DeleteMarkers() {
        //Loop through all the markers and remove
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }

        $('#add_wrk_ord').data('serialize',$('#add_wrk_ord').serialize());
        $('#t_date').datepicker({
                keyboardNavigation: false,
                forceParse: false,
                autoclose: true,
                format: "yyyy-mm-dd"
            });

        $('#wrk_typ').change(function(){
          $.ajax({
              type: "POST",
              url: "<?php echo base_url($this->session->userdata('forajax') . '/get_customers'); ?>",
              data: {"wo_type": $('#wrk_typ').val()},
              dataType: 'json',
          success: function(data){
              var tmp = "";
                    $.each(data, function(i, item) {
                              tmp += "<option value='"+data[i].account_id+"'>"+data[i].acct_name+"</option>";
                      });
                    $('#acct_name').html(tmp).trigger("chosen:updated");
                  }
          });
      });

      function get_acct(){
          $.ajax({
              type: "POST",
              url: "<?php echo base_url($this->session->userdata('forajax') . '/get_customers'); ?>",
              data: {"wo_type": $('#wrk_typ').val()},
              dataType: 'json',
          success: function(data){
              var tmp = "";
                    $.each(data, function(i, item) {
                              tmp += "<option value='"+data[i].account_id+"'>"+data[i].acct_name+"</option>";
                      });
                    $('#acct_name').html(tmp).trigger("chosen:updated");
                  }
          });
      }

      $('#add_dev_btn').click(function(){
          $(this).slideUp();
          $('#device_window').slideToggle();
          initialize();
      });
      $('#cancel_add_device').click(function(){
        $('#dlat , #dlng').val('');
        $('#add_dev_btn').slideDown();
        $('#device_window').slideToggle();

      });

      $('#save_device').click(function(){
        if($("#device_form").valid() == true){
         $.ajax({
              url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_dev'); ?>",
              method:'post',
              data: $('#device_form').serialize()+'&'+$.param({ 'account_id': $('#acct_id').val(), 'maintain_id' : $('#maintain_id').val() }),
              dataType:'json',
              success: function (data) {
                  if(data.err == 1){
                      $('#save_device').removeAttr('disabled');
                      notifymsg('danger','<b>Error</b>: '+data.msg);
                  }else{
                      $('#save_device').attr('disabled',true);
                      $('#cancel_add_device').attr('disabled',true);
                      $("#device_form").find(':input:not(:disabled)').prop('disabled',true);
                      $("#device_form").find('select').prop('disabled',true);
                      $('.chosen-select').trigger('chosen:updated');
                      notifymsg('success','<b>Success</b>: Device saved.');
                  }
              },beforeSend: function(){
                $('#save_device').attr('disabled',true);
              }
           });
        }
      });

        $.validator.setDefaults({ ignore: ":hidden:not(select)" });
            $("#device_form").validate({
                 rules: {
                     item_num: {
                        required: true
                     },
                     dev_type: {
                        required: true
                     },
                     model_number: {
                        required: true
                     },
                     serial_number: {
                        required: true
                     }
                 }
            });
            $("#add_wrk_ord").validate({
                 rules: {
                     wo_maintain_type: {
                          required: true
                     },
                     wo_assign: {
                         required: true
                     },
                     wo_acct_name: {
                         required: true
                     },
                     wo_target_date: {
                         required: true
                     }
                 },
                 submitHandler: function(form){
                       $.ajax({
                            type: "POST",
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_work_order'); ?>",
                            data: $('#add_wrk_ord').serialize(),
                            dataType: 'json',
                        success: function(data){
                                if(data[0].error != 1){
                                    notifymsg("success",". . .Work Order Added");
                                    $('#sads').attr('disabled',true);
                                    $('#add_wrk_ord #wrk_typ').attr('disabled',true);
                                    $('#add_wrk_ord #acct_name').attr('disabled',true);
                                    $('#add_wrk_ord #assgn_to').attr('disabled',true);
                                    $('#add_wrk_ord #t_date').attr('disabled',true);
                                    $('.chosen-select').trigger('chosen:updated');
                                    $('#cancel_add').remove();
                                    $("#complete_btn").show();
                                    $('#acct_id').val($('#acct_name').val());
                                    $("#maintain_id").val(data[0].id);
                                    add_device();
                                    
                                    // close_add(); active_search();
                                 }else{
                                  notifymsg("danger",data[0].msg);
                                 }
                            }
                        });
                 }
             });
        $("#complete_btn").click(function(event) {
          /* Act on the event */
          close_add(); active_search();
        });

        function add_device(){
          if($('#wrk_typ').val() == 'NEW' || $('#wrk_typ').val() =='REP'){
            //$('#device_window').slideDown();
            $('#add_dev_btn').show();
          }else{close_add(); active_search();}
        }
        function alert_cancel(){
            if($('#add_wrk_ord').serialize()!=$('#add_wrk_ord').data('serialize')){
                swal({
                    title: "Are you sure?",
                    text: "Your work will not be save",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Leave",
                    cancelButtonText: "Stay",
                    closeOnConfirm: true,
                    closeOnCancel: true },
                function (isConfirm) {
                    if (isConfirm) {
                        close_add(); active_search();
                        notifymsg("hide","hide");
                    } else {
                        swal("Cancelled");
                    }
                });
                }else{
                close_add(); active_search();
                notifymsg("hide","hide");
            }
        }

        $('#cancel_add').click(function(){
            alert_cancel();
        });

        $('#addX').click(function(){
            alert_cancel();
        });


    });
</script>